<template>
  <div>
    <input v-if="emFileInputVisible" ref="fileInput" type="file" :multiple="multiple" style="display: none"
           v-on:change="fileInputChange($event)" :accept="inputAccept" />
    <el-tooltip v-if="limitTip" class="item" effect="dark" :content="limitTip" placement="top">
      <el-button type="primary" @click="selectFile" size="small">{{ dataButtonText }}</el-button>
    </el-tooltip>
    <el-button v-else type="primary" @click="selectFile" size="small">{{ dataButtonText }}</el-button>

    <el-dialog
        :title="dataButtonText + '进度'"
        :visible.sync="queueVisible "
        width=""
        :close-on-click-modal="false"
        :show-close="false"
        append-to-body
    >
      <div v-if="queueReFresh ">
        <el-row v-for="(file,index) in (uploadQueue || {})" :key="index">
          <el-col :span="10"><span v-text="file.name"></span></el-col>
          <el-col :span="10">
            <el-progress :percentage="file.uploadPercentage || 0" class="w-75"></el-progress>
          </el-col>
          <el-col :span="4">
            <el-button
                v-on:click="removeUploadQueue(file.id||'')"
                type="text"
                icon="el-icon-error"
                size="mini"
                class="text-danger m-0 p-0"
            >
              终止
            </el-button>
          </el-col>


        </el-row>
      </div>
      <el-button v-if="multiple" type="primary" @click="selectFile">添加上传</el-button>
    </el-dialog>
  </div>


</template>
<style>

</style>
<script>
import LeUtils from '../services/le-utils'
import ApiUploader from '../services/api-uploader'

export default {
  props: {
    fileDisk: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    selectFileCallback: {
      type: Function,
      default: null
    },
    dataButtonText: {
      type: String,
      default: '上传'
    },
    accept: {
      type: String,
      default: '*.*'
    },
    urlAbsolute: {
      type: Boolean,
      default: false
    },

  },
  data() {
    return {
      uploader: null,
      inputAccept:"*.*",
      limitTip:"",
      uploadButtonDisabled: false,
      uploadQueue: {},
      connector: {},
      queueVisible: false,
      queueReFresh: true,
      emFileInputVisible: true,
    }
  },
  created() {
    let _this = this;

    //console.log(this);
    //console.log(_this.fileDisk)

    if (LeUtils.isUrl(_this.fileDisk)) {
      _this.uploader = ApiUploader.createUploaderForApi(_this.fileDisk,_this.urlAbsolute);
    } else {
      _this.uploader = ApiUploader.createUploaderForDisk(_this.fileDisk,_this.urlAbsolute);
    }

    _this.uploader.onUploaderReady = function (uploader){
      let limitExts = uploader.limitExts()
      if(!LeUtils.isEmpty(limitExts) && LeUtils.typeIs('array',limitExts)){
        let _limitExts = [];
        limitExts.forEach(function (_ext){
          _limitExts.push('.'+_ext)
        })
        _this.inputAccept = _limitExts.join(',')
      }else{
        _this.inputAccept = _this.accept
      }
      _this.limitTip = uploader.limitTip()
    };

    _this.uploader.messageHandle = function (msg,type){

      if('error' == type){
        _this.$message({
          showClose: true,
          message: msg,
          type: 'error'
        });
      }else if('success' == type){
        _this.$message({
          showClose: true,
          message: msg,
          type: 'success'
        });
      }else if('warning' == type){
        _this.$message({
          showClose: true,
          message: msg,
          type: 'warning'
        });
      }else{
        _this.$message({
          showClose: true,
          message: msg,
          type: 'info'
        });
      }
    }

    _this.uploader.onFileQueued = function (file) {
      _this.$set(_this.uploadQueue, file.id, file)
      _this.queueReFresh = false
      _this.$nextTick(() => {
        _this.queueReFresh = true
      })
    };
    _this.uploader.onFileDequeued = function (file) {
      _this.$delete(_this.uploadQueue, file.id);
      _this.queueReFresh = false
      _this.$nextTick(() => {
        _this.queueReFresh = true
      })
    };
    _this.uploader.onUploadBeforeSend = function (object, data, headers) {

    };
    _this.uploader.onUploadProgress = function (file, percent) {
      //debugger
      percent = Math.floor(percent / 5) * 5;
      let uploadQueueFile = LeUtils.valueGet(_this.uploadQueue, file.id, {})
      if (percent > LeUtils.valueGet(uploadQueueFile, 'uploadPercentage', 0)) {
        uploadQueueFile.uploadPercentage = percent;
        _this.$set(_this.uploadQueue, file.id, uploadQueueFile)
        _this.queueReFresh = false
        _this.$nextTick(() => {
          _this.queueReFresh = true
        })
      }
    };
    _this.uploader.onUploadSuccess = function (file, res) {
      var reStatus = res.status || false;
      if (reStatus) {
        _this.$emit('upload-success', LeUtils.valueGet(res, 'data'))

      }
    };
    _this.uploader.onUploadComplete = function (file) {
      _this.$delete(_this.uploadQueue, file.id);
      _this.queueReFresh = false
      _this.$nextTick(() => {
        _this.queueReFresh = true
      })
    };
    _this.uploader.onUploadFinished = function (file) {
      _this.uploadButtonDisabled = false;
      _this.queueVisible = false;
    };
  },
  mounted() {
    let _this = this;
    /*this.$on('fileUploader.selectFile', function (event) {
      return _this.selectFile(name);
    });*/

  },
  methods: {
    selectFile: function (event) {
      let _this = this;
      if (event) event.preventDefault()
      if (LeUtils.typeIs('function', this.selectFileCallback)) {
        let fileReturn = this.selectFileCallback();
        if (fileReturn instanceof Promise) {
          fileReturn.then(function (sFile) {
            if (sFile instanceof File) {
              _this.addUploadQueue(sFile)
            }
          })
        } else if (fileReturn instanceof File) {
          _this.addUploadQueue(fileReturn)
        }


        return;
      }

      if (typeof this.$refs['fileInput'] != "undefined") {
        this.$refs['fileInput'].click();
      }
      return;
    },
    fileInputChange: function (event) {
      if (event) event.preventDefault();

      let _this = this;

      if (!_this.uploader.isReady) {
        _this.$message.error('上传错误,请稍候再试');
        return false;
      }


      let emFileInput = this.$refs['fileInput'];

      _this.emFileInputVisible = false;

      _this.$nextTick(function () {
        _this.emFileInputVisible = true;
      });

      let _files = emFileInput.files || new FileList;
      //console.log(_files);
      if (_files.length <= 0) {
        return false;
      }

      for (let i = 0; i < _files.length; i++) {
        let file = _files[i];
        //console.log(file)
        _this.addUploadQueue(file)
      }

    },
    addUploadQueue: function (file) {
      let _this = this;

      _this.uploadButtonDisabled = true;
      _this.queueVisible = true;

      _this.uploader.addUploadQueue(file, function (file, res) {

      }, function (file, res) {
        //_this.removeUploadQueue(file.id);
        _this.uploadButtonDisabled = false;
      })

    },
    removeUploadQueue: function (file) {
      this.uploader.removeUploadQueue(file);
      //console.log(queue_key,this.uploadQueue);
    },
    startUpload: function () {
      this.uploader.startUpload();
      this.uploadButtonDisabled = true;
    },
    stopUpload: function () {
      this.uploader.stopUpload(true);
      this.uploadButtonDisabled = false;
    },
    cancelUpload: function () {
      this.uploader.reset();
      this.uploadQueue = {};
      this.uploadButtonDisabled = false;
    },


  }


}
</script>
